package firstping.cron;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import firstping.data.QnAPersistenceManager;
import firstping.model.Domain;
import firstping.model.SaveDomain;

@SuppressWarnings("serial")
public class CheckServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
		PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
		String name = req.getParameter("name");
		name=URLDecoder.decode(name,"UTF-8");
		String email = req.getParameter("email");
		email=URLDecoder.decode(email,"UTF-8");
		
		Query query = psm.newQuery(Domain.class);
		query.setFilter("name=='"+name+"' && email=='"+email+"'");
		@SuppressWarnings("unchecked")
		List<Domain> check = (List<Domain>) query.execute();

		try {
            URL url = new URL(name);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			connection.setRequestProperty("Accept-Charset", "	ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			connection.setRequestProperty("Connection", "keep-alive");
			connection.setRequestProperty("Keep-Alive", "115");
			connection.setRequestProperty("Cookie", "PREF=ID=987bb7a56b1cc7bc:U=691fa246d56f502e:FF=0:TM=1314876638:LM=1314876681:S=yBXzqp_WQq9ykX-j; NID=50=nfNXg7ymSSsfdzMnkEuo7t1GCgIEwcK5xmpFhu1mQWwvNI5nFHLZpRsy_1XnaoKrdj9hnz7za9-M2OIO99phfFSTmXln-xCvqzJaRWHsN0EQKgpmkvgUDTWPVF4I4c9L; SID=DQAAALcAAADhqr-J8Ls3CKhmbRjwTMMP1DjmIvR8qBFxv99saTaFFgoRsVf18W4p_BTocYoxYNMvsvh9sfjMj7KqLyd_s9Y0lwYY_Rrljd7t5IpKBTWWnsv9VSJ_qelH943zV8YIT3uuIdJbHhFlCnVEu_YealZoldWjf4VirYR0PIrr0i4_JU2JCHRmpyW0ACt3KcyLkukJlGDyT5yC5js3CBSTAhnWSylBpMWPWyWJzqXe2BQFcdfuU_qo00pAR-uEcMQ437M; HSID=A9Z-j3CKhzDEykAES");
			connection.setRequestProperty("Cache-Control", "max-age=0");

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	SaveDomain save = new SaveDomain();
            	save.setName(name);
            	save.setStatus("True");
            	String longDate = String.valueOf(new Date().getTime());
            	save.setLongDate(longDate);
            	psm.makePersistent(save);
            	
            	if(check.size()>0)
        		{
        			Date update = new Date();
        	    	Date up = new Date(update.getTime()+check.get(0).getRequest()*60*1000);
        	    	String status = check.get(0).getStatus(); 
        			check.get(0).setUpdate(up);
        			check.get(0).setStatus("True");
        			psm=JDOHelper.getPersistenceManager(check.get(0));
        			psm.currentTransaction().begin();
        			psm.makePersistent(check.get(0));
        			psm.currentTransaction().commit();
        			if(!status.equals("True"))
        			{
        				Properties props = new Properties();
        		        Session session = Session.getDefaultInstance(props, null);

        		        String emails = "Firstping.com support";
        		        String text = "<b>URL:</b> <a href='"+name+"'>"+name+"</a> <br/> <b>Time:</b> "+new Date()+" <br/><br/><b>About This Message:</b> This message was generated by Firstping.com. Your website error has been resolved";
        		        
        		        String msgBody = text;

        		        try {
        		            Message msg = new MimeMessage(session);
        		            msg.setFrom(new InternetAddress("admin@firstping.com",emails));
        		            msg.addRecipient(Message.RecipientType.TO,
        		                             new InternetAddress(email,email));
        		            msg.setSubject("Recovery Alert");
        		            msg.setContent(msgBody, "text/html");
        		            Transport.send(msg);
        		           
        		        } catch (AddressException e1) {
        		            // ...
        		        } catch (MessagingException e1) {
        		            // ...
        		        }
        			}
        		}
            }
        } catch (MalformedURLException e) {
        	
        } catch (IOException e) {
        	SaveDomain save = new SaveDomain();
        	save.setName(name);
        	save.setStatus("False");
        	String longDate = String.valueOf(new Date().getTime());
        	save.setLongDate(longDate);
        	psm.makePersistent(save);
        	if(check.size()>0)
    		{
    			Date update = new Date();
    	    	Date up = new Date(update.getTime()+check.get(0).getRequest()*60*1000);
    	    	String status = check.get(0).getStatus();
    			check.get(0).setUpdate(up);
    			check.get(0).setStatus("False");
    			psm=JDOHelper.getPersistenceManager(check.get(0));
    			psm.currentTransaction().begin();
    			psm.makePersistent(check.get(0));
    			psm.currentTransaction().commit();
    			if(!status.equals("False"))
    			{
    				Properties props = new Properties();
    		        Session session = Session.getDefaultInstance(props, null);

    		        String emails = "Firstping.com support";
    		        String text = "<b>URL:</b> <a href='"+name+"'>"+name+"</a> <br/> <b>Time:</b> "+new Date()+" <br/><br/><b>About This Message:</b> This message was generated by Firstping.com. Website error alerts are generated in response to a failure to connect to your website or the server where your website is hosted. Firstping.com will monitor your website more frequently and will notify you once the error has been resolved.";
    		        
    		        String msgBody = text;

    		        try {
    		            Message msg = new MimeMessage(session);
    		            msg.setFrom(new InternetAddress("admin@showsiteinfo.com",emails));
    		            msg.addRecipient(Message.RecipientType.TO,
    		                             new InternetAddress(email,email));
    		            msg.setSubject("Error Alert");
    		            msg.setContent(msgBody, "text/html");
    		            Transport.send(msg);
    		           
    		        } catch (AddressException e1) {
    		            // ...
    		        } catch (MessagingException e1) {
    		            // ...
    		        }
    			}
    		}
        }
		
	}

}
